package com.example.controller;

import com.example.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/api")
public class VerificationCodeController {

    @Autowired
    private VerificationCodeService verificationCodeService;

    // 生成验证码图片
    @GetMapping("/generate-code-image")
    public ResponseEntity<byte[]> generateCodeImage(@RequestParam String username) {
        try {
            byte[] imageBytes = verificationCodeService.generateCodeImage(username);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            // 处理 IOException，例如记录日志或返回错误响应
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            // 处理其他异常，例如记录日志或返回错误响应
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 验证验证码
    @PostMapping("/verify-code")
    public String verifyCode(@RequestParam String username, @RequestParam String code) {
        boolean isValid = verificationCodeService.verifyCode(username, code);
        if (isValid) {
            return "验证码有效";
        } else {
            return "验证码无效或已过期";
        }
    }
}

